package fragment;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.ViewModelProvider;

import com.example.a2032.R;
import com.example.a2032.Utils.BleSdk;
import com.example.a2032.Utils.SchedulersTransformer;
import com.example.a2032.Utils.Utils;
import com.example.a2032.entity.PPGMeasureData;
import com.example.a2032.fragment.BaseFragment;
import com.example.a2032.entity.HeartRateData;
import com.example.a2032.entity.RealTimeData;
import com.example.a2032.entity.RealTimeStepData;
import com.example.a2032.viewmodel.RealTimeStepViewModel;

import java.util.Calendar;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindArray;
import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * 步数心率距离界面
 * A simple {@link Fragment} subclass.
 * Use the {@link WatchBg2Fragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class WatchBg2Fragment extends BaseFragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.tv_timeHour)
    TextView tvTimeHour;
    @BindView(R.id.tv_time_minute)
    TextView tvTimeMinute;
    @BindView(R.id.tv_date)
    TextView tvDate;
    @BindView(R.id.tv_weekDays)
    TextView tvWeekDays;
    @BindView(R.id.iv_tempStatus)
    ImageView ivTempStatus;
    @BindView(R.id.tv_WatchTempValue)
    TextView tvWatchTempValue;
    @BindView(R.id.iv_watchStep)
    ImageView ivWatchStep;
    @BindView(R.id.tv_WatchStepValue)
    TextView tvWatchStepValue;
    @BindView(R.id.iv_watchHr)
    ImageView ivWatchHr;
    @BindView(R.id.tv_WatchHrValue)
    TextView tvWatchHrValue;
    @BindArray(R.array.week_array)
    String[] weekArray;
    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private RealTimeStepViewModel realTimeStepViewModel;

    public WatchBg2Fragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @return A new instance of fragment WatchBg2Fragment.
     */
    // TODO: Rename and change types and number of parameters
    public static WatchBg2Fragment newInstance() {
        WatchBg2Fragment fragment = new WatchBg2Fragment();
        Bundle args = new Bundle();

        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_watch_bg2, container, false);
        ButterKnife.bind(this, view);
        init();
        Log.i(TAG, "onCreateView: " + modifyIndex);
        return view;
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        Log.i(TAG, "onSaveInstanceState: ");
    }

    private void init() {
        if (realTimeStepViewModel == null) {
            Log.i(TAG, "init: ");
            realTimeStepViewModel = new ViewModelProvider(this).get(RealTimeStepViewModel.class);
        }
        showDate();
        startDateTimer();
        subscribe(this);
        realTimeStepViewModel.getLastHeartRate().observe(getViewLifecycleOwner(), new androidx.lifecycle.Observer<PPGMeasureData>() {
            @Override
            public void onChanged(PPGMeasureData heartRateData) {
                if (heartRateData != null )
                    tvWatchHrValue.setText(heartRateData.getHeartRate() + "");
            }
        });

        getRealTimeData(Utils.getTodayTimeString());
    }

    androidx.lifecycle.Observer realTimeObserve = new androidx.lifecycle.Observer<RealTimeData>() {


        @Override
        public void onChanged(RealTimeData realTimeData) {
            if (realTimeData != null) {
                showSportData(realTimeData.getSteps(), 0, realTimeData.getDistance());
            }
        }
    };
    LiveData<RealTimeData> realTimeDataLiveData;

    void getRealTimeData(String date) {

        realTimeDataLiveData = realTimeStepViewModel.getLastRealTime(date);
        realTimeDataLiveData.observe(getViewLifecycleOwner(), realTimeObserve);

    }

    @Override
    public void onDetach() {
        super.onDetach();
        Log.i(TAG, "onDetach: ");
        unSubscribe(timerDisposable);
        realTimeDataLiveData.removeObservers(this);
    }


    Disposable timerDisposable;

    private void startDateTimer() {
        Observable.interval(1, TimeUnit.SECONDS).compose(SchedulersTransformer.io2MainObservable()).subscribe(new Observer<Long>() {
            @Override
            public void onSubscribe(Disposable d) {
                timerDisposable = d;
            }

            @Override
            public void onNext(Long value) {
                showDate();
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    int lastDay;
    int modifyIndex = 0;

    /**
     * 日期时间
     */
    private void showDate() {
        Calendar calendar = Calendar.getInstance();
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minutes = calendar.get(Calendar.MINUTE);
        int weekDays = calendar.get(Calendar.DAY_OF_WEEK);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        if (lastDay != 0 && lastDay != day) {
            sendData(BleSdk.setDeviceTime());
            tvDate.postDelayed(new Runnable() {
                @Override
                public void run() {
                    sendData(BleSdk.enableRealTimeStep(true, true));
                }
            },200);
            String date = Utils.getTodayTimeString();
            getRealTimeData(date);
        }
        String weekString = weekArray[weekDays - 1];
        tvTimeHour.setText(Utils.getFormatIntString(hour));
        tvTimeMinute.setText(Utils.getFormatIntString(minutes));
        tvWeekDays.setText(weekString);
        tvDate.setText(Utils.getFormatDateString(month + 1, day, "."));
        lastDay = day;
    }


    /**
     * 运动数据
     *
     * @param steps
     * @param hrValue
     */
    private void showSportData(int steps, int hrValue, float distance) {
        tvWatchStepValue.setText(String.valueOf(steps));
        tvWatchTempValue.setText(String.valueOf(distance));
    }

    @Override
    public void RealTimeData(RealTimeStepData timeStepData) {
        super.RealTimeData(timeStepData);
        int step = timeStepData.getStep();
        int heartRate = timeStepData.getHeartRate();
        float distance = timeStepData.getDistance();
        //showSportData(step, heartRate, distance);
    }

    private static final String TAG = "WatchBg2Fragment";

    @Override
    public void onResume() {
        super.onResume();
        Log.i(TAG, "onResume: ");
        sendData(BleSdk.enableRealTimeStep(true, true));
    }


}